/*选人组件*/
import { Modal, Select, Tag, Tooltip, Spin, Empty } from "antd";
import { forwardRef, useState ,useRef, useEffect} from "react";
import { getIeHack, getQuery } from "../../framework/common/utils";
import request from "../../framework/common/utils/request";
import message from "../../framework/common/utils/message";
import {buildUrl, isIE} from "../../framework/common/utils"
import clsx from "clsx";
import { useDeepCompareEffect } from "ahooks";
import eventBus from "../../framework/common/eventBus";

export default forwardRef(function({
    className,
    package_id, 
    urlPrefix="",
    CurUserGUID="",
    multiSelect = true,
    selectSelf = false,
    filterDisable = true,//是否过滤禁用用户，默认为true 过滤，只有显示声明为false时，才不过滤禁用用户
    isAddSign=false,//是否选择加签人
    CurUserDepartmentGUID = "",//当前用户部门guid
    textField = "name",//实际请求返回的text Key
    valueField = "guid",//时期静秋返回的id key
    value=[], 
    placeholder="请选择人员",//为空提示语
    status="",//校验状态
    onChange,
    maxSize = 30,//最大可选数量
    title="选择人员",//弹出框标题
    popupContainer=()=>{
      return document.querySelector(".main-content")
    },//toolTip出现的位置
    maxTagCount = false//用户超出显示范围时，是否要显示 +* 数量，这个为ant官方配置，只有发起模式抄送人有这个
  }, ref) {
  const [isVisible, setIsVisible] = useState(false);//选人弹出框显示状态  
  const selectRef = useRef(null);

  /*显示选人弹出框 */
  function showModal(){
    selectRef.current.blur();
    setIsVisible(true);
  }

  //使用了ant select组件，返回空的下拉对象
  function getList(){
    return <></>
  }

  //自定义右侧 + 按钮
  function addIcon(){
    return <span className="add_icon"></span>
  }
  
  const [selectValue, setSelectValue] = useState([]);//ant select组件需要的值
  const [fieldData, setFieldData] = useState([]);//当前组件需要的值

  //设置select的value
  function setValue(data){
    let returnData = [];
    data.forEach(function(item){
        returnData.push(
          {
            value: item,
            label: item[textField],
            key: item[valueField]
          },
        );//select组件可接受这个格式的值，label为显示的恩本，value为实际的值，可接受对象，key为唯一标识即可
    })
    setSelectValue(returnData);//更新select的显示值
    setFieldData(data);//更新组件自身需要的值
    
  }//设置实际值

  useDeepCompareEffect(function(){
    setValue(value ||[]);//初始化设置默认值
  },[value]);

  /**
   * 弹出框更新数据
   * fieldData 实际字段要的值
   */
  function setData(fieldData){
    //根据textField valueField再重新包装一下后端需要的key
    fieldData = fieldData.map(function (item) {
      item[textField] = item.name;
      item[valueField] = item.guid;

      return {
        ...item, 
        ...{
          auditor_name: item[textField],
          auditor_id: item[valueField],
          station_name : item.station_name || "",
          station_guid : item.station_guid || "",
          auditor_code : item.code || ""
        }
      }
    });
    setValue(fieldData);//设置select组件的值
    onChange?.(fieldData);//更新外部表单字段的值
  }
  function handleChange(val, options) {
    var fieldData = [];
    val.map(function(item){
      fieldData.push(item.value);
    });
    setValue(fieldData);//设置select组件的值
    onChange?.(fieldData);//更新外部表单字段的值
  }

  return <>
    {
      isVisible
      && <ModalContent 
          valueField={valueField}
          textField={textField}
          maxSize={multiSelect ? maxSize : 1}
          CurUserGUID={CurUserGUID} 
          package_id={package_id} 
          urlPrefix={urlPrefix} 
          CurUserDepartmentGUID={CurUserDepartmentGUID} 
          isVisible={isVisible} 
          multiSelect={multiSelect}
          setIsVisible={setIsVisible}
          selectSelf={selectSelf}
          filterDisable={filterDisable}
          isAddSign={isAddSign}
          fieldData={fieldData}
          setData={setData}
          title={title}></ModalContent>
    }
    <Select ref={selectRef}
      maxTagCount={maxTagCount}
      className={clsx("person-select", className)}
      status={status}
      value={selectValue}
      onChange={handleChange}
      labelInValue
      optionLabelProp="station_name"
      dropdownRender={()=>{return getList()}}
      dropdownClassName={"person-select-dropdown"}
      mode="tags"
      style={{ width: '100%' }}
      placeholder={placeholder}
      suffixIcon={addIcon()}
      showArrow = {true}
      onClick={(e)=>{
        showModal();
      }}
      options={[]}
      tagRender={(props)=>{
        return TagRender({
          popupContainer: popupContainer,
          props: props//ant tagRender自带的参数
        });
      }}
      {...getIeHack()}

    >
    </Select>
  </>

})

const ModalContent = forwardRef(function ModalContent({isVisible, setIsVisible, CurUserGUID, package_id, urlPrefix, CurUserDepartmentGUID, setData, selectSelf, filterDisable, isAddSign,
  multiSelect,
  maxSize,
  value,
  textField,
  fieldData,//组件自己需要的值
  valueField,
  title
}, ref) {
  const iframeRef = useRef(null);

  function handleOk() {

    //测试用的返回数据
    // let selectData = [
    //   {"name":"吕贝贝","guid":"2422B44B-475F-E911-80CE-ECEBB898E6F7","station_guid":"","station_name":"","code":"吕贝贝","type":"ALL"},
    //   {"name":"李玉平","guid":"244299EA-234A-E911-80CD-ECEBB898E6F7","station_guid":"","station_name":"","code":"李玉平","type":"ALL"},
    //   {"name":"test042601","guid":"2CDD79C2-BA41-4570-1A38-08DA273537CB","station_guid":"12A246D2-9E2C-4F5C-0942-08DA273537CB","station_name":"集团/test0426","code":"test042601","type":"ALL"}
    // ];

    let selectData = iframeRef.current.contentWindow.window.getData();
    if(selectData.length > maxSize){
      message.info({
        content: "最多允许选择" + maxSize + "个用户"
      })
    }else{
      setData(selectData);
      setIsVisible(false);
    }
  }
  const handleCancel = () => {
    setIsVisible(false);
  };
  
  //组件配置项
  if(selectSelf === true){
    CurUserGUID = ""; 
  }

  let options={
    maxSize: maxSize,//最多可选数量
    CurUserGUID: CurUserGUID || "",//当前用户guid
    filter_disable: filterDisable ? 1: 0,//是否过滤禁用用户 1过滤 0不过滤
    isAddSign: isAddSign,//是否选择加签人
    multiSelect: multiSelect ? 1 : 0,//是否多选
    package_id: package_id
  }
  if(CurUserDepartmentGUID){
    options.buguid = CurUserDepartmentGUID;
  }

  let _openUrl = '/flowinstance/process/select-auditors';
  if (urlPrefix) {
    _openUrl = urlPrefix + _openUrl;
  }
  _openUrl = buildUrl(_openUrl, options);//给链接拼接配置项

  //每次打开前，给当前window增加orgs，用于弹出框回填
  if (fieldData && fieldData.length) {
    fieldData.forEach(function (item) {
        item.guid = item[valueField];
        item.name = item[textField];
    });
    window.parent.auditorsUsers = fieldData;
  } else {
    window.parent.auditorsUsers = null;
  }

  return (
    <Modal bodyStyle={{padding:0}} centered={true} title={title} width={960} visible={isVisible} onOk={handleOk} onCancel={handleCancel}>
      <iframe 
        ref = {iframeRef}
        src={_openUrl}
        style={{"width":"100%","height": (600-54-52)+"px"}}
      ></iframe>
    </Modal>
  );
});

//自定义select的tage
function TagRender ({
  props,//ant组件自带参数
  popupContainer//提示出现的位置
}) {
  const { label, value, closable, onClose } = props;
  return <Tooltip 
            getPopupContainer={popupContainer}
            placement="bottom" 
            color="white"
            title={<TagInfo item={value}></TagInfo>}
          >
            <Tag
              closable={closable}
              className="text-sm mysoft-tag-connect"
              onClose={onClose}
            >
              {label}
            </Tag>
          </Tooltip>;
};

//选人tag移入时，展示人的组织详情
function TagInfo({
  item
}){
  
  const [part_time, setPart_time] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(function(){
    //获得用户组织信息
    request({
      data: {
          id: item.auditor_id || item.id,
          package_id: getQuery().package_id
      },
      method: 'POST',
      url: "/organization/ou/get-user-by-id?t="+Math.random(),
    }).then(
      function(result){
        setLoading(false);
        if(result.code ==1){
          setPart_time(result.data.data);
        }
      },
      function(){
        setLoading(false);
      }
    )
  },[]);
  
  if(part_time.length <= 0){
    return <Spin spinning={loading}>
              <div  className="overflow-auto max-h-80 min-w-160px min-h-40px">
                {
                  !loading
                  && <Empty
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                      />
                }
              </div>
            </Spin>
  }

  return <div 
            onClick={(e) => {
              e.stopPropagation();//提示内容阻止冒泡，防止触发了tag的点击事件导致出现弹框
            }}
            onMouseDown={(e) => {
              e.stopPropagation();//提示内容阻止冒泡，防止触发了tag的禁止选中文本事件
            }}
            className="overflow-auto max-h-80"
          >
          {
            part_time.map(function(item){
              let name_label = item["name"].replace(/\((.*)\)/,' / $1').replace(/\</ig,'&lt;').replace(/\>/ig,'&gt;');
              return <ul className="text-xs person-tip" key={item.code}>
                        <li>
                          <span className="user_name">{name_label}/{item.code}</span>

                          {/* 默认组织 */}
                          <DefaultOrg item={item}></DefaultOrg>

                          {/* 兼职组织 */}
                          <PartTimeOrg item={item}></PartTimeOrg>

                          {/* 分管组织 */}
                          <BranchOrg item={item}></BranchOrg>
                        </li>
                      </ul>
            })
          }
        </div>
}

//默认组织
function DefaultOrg({
  item
}){
  
  return <>
    <p className="mb-0 user_title text-color-999">默认组织</p>
    <p className="user_name">
      {
        item.org_settings.length > 0
        ? item.org_settings.map(function(org){
            if(org.is_default == 1){
              return <span key={org.org_id}>{org.name_path}</span>
            }
          })
        : <>({item.station_name})</>
      }
    </p>
  </>
}

//兼职组织
function PartTimeOrg({
  item
}){
  if(item.org_settings.length > 0){
    return <>
              <p className="mb-0 user_title text-color-999">兼职组织</p>
              <div className="part_time">
                {
                  item.org_settings.map(function(org){
                    return <p className="user_name" key={org.name_path}>{org.name_path}</p>
                  })
                }
              </div>
            </>
  } else {
      return null
  }
}

//分管组织
function BranchOrg({
  item
}){
  if(item.branch_organization?.length>0){
    return <>
              <p className="mb-0 user_title text-color-999">分管组织</p>
              <div className="part_time">
                {
                  item.branch_organization?.forEach(function(org){
                    return <p className="user_name" key={org.name_path}>{org.name_path}</p>;
                  })
                }
              </div>
            </>
  }else{
    return null
  }
}